package db;

/**
 * Created by Administrator on 2016/6/20.
 */

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import entity.ContactEntityTest;
import entity.RecordEntity;

/**
 * Created by Administrator on 2016/6/17.
 */
public class DBhelper extends SQLiteOpenHelper {
    private static DBhelper self;
    public static DBhelper getInstance(Context context) {
        if (self == null) self = new DBhelper(context);
        return self;
    }

    private static final String DB_NAME = "scanner.db";
    private static final int DB_VERSION = 1;

    private static final String HISTORY_TABLE_NAME = "history";
    private static final String HISTORY_KEY_RECORD_ID = "_id";
    private static final String HISTORY_KEY_QR_TYPE = "qr_type";
    private static final String HISTORY_KEY_QR_CONTENT = "qr_content";
    private static final String HISTORY_KEY_QR_FROM = "qr_from";
    private static final String HISTORY_KEY_QR_TIME = "qr_time";

    private static final String CRATE_HISTORY_TABLE_SQL = "CREATE TABLE " + HISTORY_TABLE_NAME + " ("
            + HISTORY_KEY_RECORD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + HISTORY_KEY_QR_TYPE + " TINYINT,"
            + HISTORY_KEY_QR_CONTENT + " TEXT,"
            + HISTORY_KEY_QR_FROM + " BOOLEAN,"
            + HISTORY_KEY_QR_TIME + " DATETIME DEFAULT (datetime('now','localtime')))";


    public DBhelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CRATE_HISTORY_TABLE_SQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + HISTORY_TABLE_NAME);
        onCreate(db);
    }

    private SQLiteDatabase getDatabase() {
        SQLiteDatabase db = null;
        try {
            db = getWritableDatabase();
        } catch (SQLiteException e) {
            Log.e("SamLog", "数据库操作失败");
            e.printStackTrace();
        }
        return db;
    }

    public boolean insertRecord(RecordEntity recordEntity) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(HISTORY_KEY_RECORD_ID, recordEntity.getID());
        RecordEntity.RECORD_TYPE recordType = recordEntity.getRecord_type();
        contentValues.put(HISTORY_KEY_QR_TYPE, recordType.getTypeValue());
        if (recordType == RecordEntity.RECORD_TYPE.CONTACT) {
            contentValues.put(HISTORY_KEY_QR_CONTENT, ((ContactEntityTest) recordEntity.getRecordContent()).toString());
        } else {
            contentValues.put(HISTORY_KEY_QR_CONTENT, ((String) recordEntity.getRecordContent()));
        }
        contentValues.put(HISTORY_KEY_QR_FROM, recordEntity.getRecord_from().getValue());
        contentValues.put(HISTORY_KEY_QR_TIME, recordEntity.getRecordTime());
        return getDatabase().insert(HISTORY_TABLE_NAME, null, contentValues) != -1;

    }

    public void deleteRecord(int recordId) {
        getDatabase().delete(HISTORY_TABLE_NAME, HISTORY_KEY_RECORD_ID + " = ", new String[]{recordId + ""});
    }

    public List<RecordEntity> getAllRecords() {
        Cursor cursor = getDatabase().rawQuery("SELECT * FROM " + HISTORY_TABLE_NAME, null);
        List<RecordEntity> recordEntityList = null;
        if (cursor != null) {
            recordEntityList = new ArrayList<>();
            while (cursor.moveToNext()) {
                RecordEntity recordEntity = new RecordEntity();
                recordEntity.setID(cursor.getInt(cursor.getColumnIndex(HISTORY_KEY_RECORD_ID)));
                RecordEntity.RECORD_TYPE recordType = RecordEntity.RECORD_TYPE.parseFromValue(cursor.getInt(cursor.getColumnIndex(HISTORY_KEY_QR_TYPE)));
                recordEntity.setRecord_type(recordType);
                recordEntity.setRecordContent(cursor.getColumnIndex(HISTORY_KEY_QR_CONTENT));
                RecordEntity.RECORD_FROM recordFrom = RecordEntity.RECORD_FROM.parseFromValue(cursor.getInt(cursor.getColumnIndex(HISTORY_KEY_QR_TYPE)));
                recordEntity.setRecord_from(recordFrom);
                String time = cursor.getString(cursor.getColumnIndex(HISTORY_KEY_QR_TIME));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                long timeStamp = System.currentTimeMillis();
                try {
                    timeStamp = simpleDateFormat.parse(time).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                recordEntity.setRecordTime(timeStamp);
                recordEntityList.add(recordEntity);
            }
        }
        return recordEntityList;
    }
}